<?php

namespace app\api\controller;

use app\admin\model\Personnel;
use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Session;
use app\admin\model\AuthDepartment;
use fast\Tree;
/**
 * 运动轨迹接口
 */
class Trajectory extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public $app;


	/**
     * 公共
	 * @author gzy
	 * @date   2018年8月12日 09:15:00
     */
	public function _initialize(){
	
        parent::_initialize();
		//获取默认值
		$this->config = $this->getConfig($this->getDefault('Trajectory'));
		$this->auth = \app\admin\library\Auth::instance();
		//退出
		//print_r($this->auth->logout());die; 
        //模拟登陆
		//$this->auth->IndexLogin('ceshi');
		//判断权限
		//print_r($this->auth->check('see/index'));die;
	}
	public function mologin(){
		$this->auth->IndexLogin('001');
	}
    /**
     * 首页
     */
    public function index(){	
		 //模拟登陆
		 //$this->auth->IndexLogin('001');
		 $this->auth->logout();
		 // 检测是否需要验证登录
		 return redirect($this->request->domain().'/api/trajectory/oauth');
         
    }
	//获取部门人员
	public function getDeptList(){
		header('Access-Control-Allow-Credentials:true');
		if (!$this->auth->isLogin()){
			$this->error(__('Please login first'), null, -6	);
		}
		if(!$this->auth->check('see/index')) $this->error(__('You have no permission'), null, -4);
		//获取默认参数 user
		$UserConfig = $this->getConfig($this->getDefault('User'));
		//初始化
		$app = Factory::work($UserConfig);
		$dept = GetBaseInfo('Dept');
		$id = $this->request->get("id");
		if($this->auth->check('see/all')){
			$msg = 'all';
			$groupList = [];
			if(empty($id)){
				$groupList['deptinfo'] = array_column(collection(AuthDepartment::field('id,name,delete_status,parentid as pid')->where('id','in',''.implode(',',$dept).'')->select())->toArray(),null,'id');
			}else{
				$groupList['deptinfo'] = array_column(collection(AuthDepartment::field('id,name,delete_status,parentid as pid')->where('parentid','in',''.$id.'')->select())->toArray(),null,'id');
				$msg = 'dept';
				//$info = $app->user->getDepartmentUsers($id);
				$userinfo = array_column(TableListSqlQuery('User','find_in_set('.$id.',department)','username,userid,avatar'),null,'userid');
				if(!empty($userinfo)) $groupList['userinfo'] = $userinfo;
			
			}
			if(empty($groupList)) $this->error(GetErrorLang('-1'));
			//print_R( $groupList);die;
			//print_R($groupList);die;
			$this->success($msg, $groupList);
		}elseif($this->auth->check('see/dept')){
			$userid = \think\Session::get('admin')['userid'];
		    $department = TableField('Admin','department',$userid,'userid');
			$groupList = [];
			if(empty($department)) $this->error(GetErrorLang('-1'));
			if(empty($id)){
				$group = array_column(collection(AuthDepartment::field('id,name,delete_status,parentid as pid')->where('id','in',''.$department.'')->select())->toArray(),null,'id');
			}else{
				if(!ValueExists($id,$department))  $this->error(__('You have no permission'), null, -4);
				$group = array_column(collection(AuthDepartment::field('id,name,delete_status,parentid as pid')->where('parentid','in',''.$id.'')->select())->toArray(),null,'id');
				$userinfo = array_column(TableListSqlQuery('User','find_in_set('.$id.',department)','username,userid,avatar'),null,'userid');
				if(!empty($userinfo)) $groupList['userinfo'] = $userinfo;
			}
			$position = [];
			$groupList['deptinfo'] = [];
			foreach($group as $key=>$val){
				if($val['pid']!='2'  && !in_array($val['pid'],$dept)){
					continue;
				}elseif($val['pid'] == '2' && !in_array($val['id'],$dept)){
					continue;
				}
				if(in_array($val['id'],$dept)){
					$position['id'] = $val['id'];
				}elseif(in_array($val['pid'],$dept)){
					$position['pid'] = $val['pid'];	
				}
				$groupList['deptinfo'][] = $val;
			}
			//print_r($groupList['deptinfo']);die;
			$groupList['deptinfo'] = array_column($groupList['deptinfo'],null,'id');
			Tree::instance()->init($groupList['deptinfo']);
			if(empty($groupList['deptinfo'])) $this->error(GetErrorLang('-2'),null,-2);
			   $groupdata = [];
			  if(isset($position['id'])){
				$msg = 'all';
			  }elseif(isset($position['pid'])){
				$msg = 'dept';
			  }else{
				$this->error(GetErrorLang('-1'),null,-1);
			  }
			if(empty($groupList['deptinfo']))  $this->error(GetErrorLang('-2'),null,-2);
			$this->success($msg, $groupList);
		
		}elseif($this->auth->check('see/one')){
			$userid = \think\Session::get('admin')['userid'];
			if(empty($userid)) $this->error(__('Please login first'), null, -6);
			$groupList = [];
			$userinfo = array_column(TableListSqlQuery('User',"userid = '".$userid."'",'username,userid,avatar'),null,'userid');
			if(!empty($userinfo)){ 
				$groupList['userinfo'] = $userinfo;
			}else{
				$this->error(GetErrorLang('-5'));	
			}
			$this->success('one', $groupList);
		}else{
			$this->error(__('You have no permission'), null, -4);
		}
	}
	//获取部门人员
	public function getUserList(){
		header('Access-Control-Allow-Credentials:true');
	
		if (!$this->auth->isLogin()){
			$this->error(__('Please login first'), null, -6);
		}
		if(!$this->auth->check('see/index')) $this->error(__('You have no permission'), null, -4);
		//获取默认参数 user
		$UserConfig = $this->getConfig($this->getDefault('User'));
		//初始化
		$app = Factory::work($UserConfig);
		$id = $this->request->get("id");
		if(empty($id)) $this->error(GetErrorLang('-2'),null,-2);
		//$userid = \think\Session::get('admin')['userid'];
		//$department = TableField('Admin','department',$userid,'userid');
		//if(!ValueExists($id,$department))  $this->error(__('You have no permission'), null, 403);
		$groupList = [];
		$userinfo = array_column(TableListSqlQuery('User','find_in_set('.$id.',department)','username,userid,avatar'),null,'userid');
		if(!empty($userinfo)) $groupList['userinfo'] = $userinfo;
		$this->success('人员信息', $groupList);
	}
	/*
	//获取部门人员
	public function getDeptList(){
		header('Access-Control-Allow-Credentials:true');
		if (!$this->auth->isLogin()){
			$this->error(__('Please login first'), null, 401);
		}
		if(!$this->auth->check('see/index')) $this->error(__('You have no permission'), null, 403);
		//获取默认参数 user
		$UserConfig = $this->getConfig($this->getDefault('User'));
		//初始化
		$app = Factory::work($UserConfig);
		$dept = ['14','15','16','17'];
		if($this->auth->check('see/all')){
			$groupList = collection(AuthDepartment::field('id,name,delete_status,parentid as pid')->where('id','in',''.implode(',',$dept).'')->whereOr('parentid','in',''.implode(',',$dept).'')->select())->toArray();
			Tree::instance()->init($groupList);
			if(empty($groupList)) $this->error(GetErrorLang('-1'));
			$groupdata = [];
			$result = Tree::instance()->getTreeArray(2);

			foreach ($result as $key => &$val){
				$info = $app->user->getDepartmentUsers($val['id']);
				if(!empty($info['userlist'])) $val['userinfo'] = $info['userlist'];
				unset($info);
				if(!empty($val['childlist'])){
					foreach($val['childlist'] as $k=>&$v){
						$info = $app->user->getDepartmentUsers($v['id']);
						if(!empty($info['userlist'])) $v['userinfo'] = $info['userlist'];
						unset($v['childlist']);
						unset($info);
					}
				}else{
					unset($val['childlist']);
				}
			}
			if(empty($result)) $this->error(GetErrorLang('-1'));
			$this->success('all', $result);
		}elseif($this->auth->check('see/dept')){
			$msg = 'dept';
			$userid = \think\Session::get('admin')['userid'];
		    $department = TableField('Admin','department',$userid,'userid');
			if(empty($department)) $this->error(GetErrorLang('-1'));
			$groupList = collection(AuthDepartment::field('id,name,delete_status,parentid as pid')->where('id','in',''.$department.'')->whereOr('parentid','in',''.$department.'')->select())->toArray();
			$group = [];
			$position = [];
			foreach($groupList as $key=>$val){
				if($val['pid']!='2'  && !in_array($val['pid'],$dept)){
					continue;
				}elseif($val['pid'] == '2' && !in_array($val['id'],$dept)){
					continue;
				}
				if(in_array($val['id'],$dept)){
					$position['id'] = $val['id'];
				}elseif(in_array($val['pid'],$dept)){
					$position['pid'] = $val['pid'];	
				}
			
				$group[] = $val;
			}
			Tree::instance()->init($group);
			if(empty($group)) $this->error(GetErrorLang('-1'));
			   $groupdata = [];
			  if(isset($position['id'])){
				$result = Tree::instance()->getTreeArray(2);
				$msg = 'all';
			  }elseif(isset($position['pid'])){
				$result = Tree::instance()->getTreeArray($position['pid']);
			  }else{
				$this->error(GetErrorLang('-1'));
			  }
			foreach ($result as $key => &$val){
				$info = $app->user->getDepartmentUsers($val['id']);
				if(!empty($info['userlist'])) $val['userinfo'] = $info['userlist'];
				unset($info);
				if(!empty($val['childlist'])){
					foreach($val['childlist'] as $k=>&$v){
						$info = $app->user->getDepartmentUsers($v['id']);
						if(!empty($info['userlist'])) $v['userinfo'] = $info['userlist'];
						unset($v['childlist']);
						unset($info);
					}
				}else{
					unset($val['childlist']);
				}
			}
		
			if(empty($result)) $this->error(GetErrorLang('-1'));
			$this->success($msg, $result);
		
		}elseif($this->auth->check('see/one')){
			$userid = \think\Session::get('admin')['userid'];
			if(empty($userid)) $this->error(__('Please login first'), null, 401);
			$result = $app->user->get($userid);
			$this->success('one', $result);
		}
		//print_r(\think\Session::get('admin'));die;
	}*/
	//获取人员定位信息
	public function getInfo(){
		header('Access-Control-Allow-Credentials:true');
		if (!$this->auth->isLogin()){
			$this->error(__('Please login first'), null, -6);
		}
		//if($this->request->isPost()) {

	   $data = [];
	   $params = [];
	   $params['ak'] = 'mFc5tyHtunGFoHDXf58w2y22BiuMztQR';
	   $params['service_id'] = '203337';
	   $userid = $params['entity_name'] =  $this->request->get("userid",'zhangwei');
	   $data['userinfo']['userid'] = $userid;
	   $data['userinfo']['username'] = TableField('Admin','username',$userid,'userid');
	   if(empty($data['userinfo']['username'])) $this->error(__('You have no permission'), null, -4);
	   $data['userinfo']['avatar'] = TableField('Admin','avatar',$userid,'userid');
	   $data['userinfo']['department'] = GetExplode(explode(',',TableField('Admin','department',$userid,'userid')),'AuthDepartment');
	   $data['userinfo']['position'] = TableField('Admin','position',$userid,'userid');
	  //if(empty($userid)) $this->error(GetErrorLang('-2'),null,-2);
	   //$userid = \think\Session::get('admin')['userid'];
		//$department = TableField('Admin','department',\think\Session::get('admin')['userid'],'userid');
		//if(!ValueExists( $data['userinfo']['department'],$department))  $this->error(__('You have no permission'), null, 403);
	   $date =  $this->request->get("datetime",date('Y/m/d'));
	   $date = date('Y/m/d',strtotime($date));
	   $dateInfo = GetTrajectory($date);
	   $url = "http://yingyan.baidu.com/api/v3/track/gettrack";
		
	   $i = 1;
	   $time = time();
	   foreach($dateInfo as $key=>&$val){
		   $val['info'] = [];
		   if($val['start_time'] <= $time){
			   if($i == 1){
					$params['start_time'] = $val['start_time'];
					$params['end_time'] = $val['end_time'];
					$info = \fast\Http::get($url,$params);
					if(!empty($info)){ 
						$info = json_decode($info);
						if($info->status != 0) $i++;
						if(!empty($info->points)){
							$info = $info->points[0];
							$url2 = "http://api.map.baidu.com/geocoder/v2/?location=".$info->latitude.",".$info->longitude."&output=json&ak=".$params['ak']."";
							$info = \fast\Http::get($url2);
							if(!empty($info)){ 
								$info = json_decode($info);
								if($info->status == 0){
									$val['info']['location']['lng'] = $info->result->location->lng;
									$val['info']['location']['lat'] = $info->result->location->lat;
									$val['info']['business'] = $info->result->business;
									$val['info']['formatted_address'] = $info->result->formatted_address;
								}
							}
							unset($url2);
						}
					}
					unset($params['start_time'],$params['end_time'],$info);
			   }
		   }else{
			    unset($dateInfo[$key]);
				continue;
		   }
	   }
		
	    if(empty($dateInfo)) $this->error(GetErrorLang('-1'),null,-1);
	    $data['trajectory'] = $dateInfo;
	   //print_R($data);die;
		$this->success($userid.' 详情信息', $data);
		//}else{
		//	$this->error(GetErrorLang('-2'));
		//}
	}
	//获取人员定位信息
	public function getInfo2(){
		header('Access-Control-Allow-Credentials:true');
		if (!$this->auth->isLogin()){
			$this->error(__('Please login first'), null, -6);
		}
		//if($this->request->isPost()) {
		   $params = [];
		   $params['ak'] = 'mFc5tyHtunGFoHDXf58w2y22BiuMztQR';
		   $params['service_id'] = '203337';
		   $userid = $params['entity_name'] =  $this->request->get("userid",'yangliu');
		   if(empty($userid)) $this->error(GetErrorLang('-2'));
		   $date =  $this->request->get("datetime",date('Y/m/d'));
		  // $params['start_time'] = strtotime(date('Y-m-6 09:00:59'))
		   $dateInfo = GetTrajectory($date);

		   $url = "http://yingyan.baidu.com/api/v3/track/gettrack";
		   //$params['start_time'] = strtotime(date('Y-m-6 09:00:59'));
		   //$params['end_time'] = strtotime(date('Y-m-6 23:59:59'));
		   //$info = \fast\Http::get($url,$params);
		
		   $i = 1;
		   foreach($dateInfo as $key=>&$val){
			     $val['info'] = [];
			   if($i == 1){
					$params['start_time'] = $val['start_time'];
					$params['end_time'] = $val['end_time'];
					$info = \fast\Http::get($url,$params);
					if(!empty($info)){ 
						$info = json_decode($info);
						if($info->status != 0){
							$i++;
							continue;
						}
						if(!empty($info->points)){
							$info = $info->points[0];
							$url2 = "http://api.map.baidu.com/geocoder/v2/?location=".$info->latitude.",".$info->longitude."&output=json&ak=".$params['ak']."";
							$info = \fast\Http::get($url2);
							if(!empty($info)){ 
								$info = json_decode($info);
								if($info->status == 0){
									$val['info']['location']['lng'] = $info->result->location->lng;
									$val['info']['location']['lat'] = $info->result->location->lat;
									$val['info']['business'] = $info->result->business;
									$val['info']['formatted_address'] = $info->result->formatted_address;
								}
							}
							unset($url2);
						}
					}
					unset($params['start_time'],$params['end_time'],$info);
			   }
		   }
		   print_R($dateInfo);die;
		   print_R(count($dateInfo));die;
		   if(empty($dateInfo)) $this->error(GetErrorLang('-1'));
			$this->success($userid.' 详情信息', $dateInfo);
		//}else{
		//	$this->error(GetErrorLang('-2'));
		//}
	
	}
    public function oauth(){
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->config['corp_id']."&redirect_uri=".$this->config['oauth']['callback']."&response_type=code&scope=".$this->config['oauth']['scopes']."&agentid=".$this->config['agent_id']."&state=STATE#wechat_redirect";
        return redirect($url);
    }

    public function login(){
		$app = Factory::work($this->config);
		$token = $app->access_token->getToken();//获取企业微信token
		$code = $this->request->request('code');
		$url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
		$user = \fast\Http::get($url);
		if(!empty($user)) $user = json_decode($user,true);
		
		if($user['errcode'] == 0){
			if(isset($user['UserId'])){
				if(!$this->auth->IndexLogin($user['UserId'])){
					echo '您的账户不存在，请联系管理员';die;
				}else{
					//print_r(\think\Session::get('admin')['userid']);die;
					return redirect($this->request->domain().'/trajectory');
				}
			}
		}else{
			return redirect($this->request->domain().'/api/trajectory/oauth');
		}
    }
	public function datetime(){
		header('Access-Control-Allow-Credentials:true');
		$day = [];
	    for($i = 1;$i<=31;$i++){
			$day['zc'][$i]['id'] = $i;
			$day['zc'][$i]['title'] = $i.'日';
		}
		for($i = 1;$i<=30;$i++){
			$day['bzc'][$i]['id'] = $i;
			$day['bzc'][$i]['title'] = $i.'日';
		}
		$mon = [];
	    for($i = 1;$i<=12;$i++){
			$mon[$i]['id'] = $i;
			$mon[$i]['title'] = $i.'月';
			switch ($i) {
				 case 2:
				 case 4:
				 case 6:
				 case 9:
				 case 11:
					$mon[$i]['children'] = $day['bzc'];
					break;
				default:
					$mon[$i]['children'] = $day['zc'];
					break;
			 }
		}
		$year = [];
		for($y = 2018; $y<=2025;$y++){
			$year[$y]['id'] = $y;
			$year[$y]['title'] = $y.'年';
			$year[$y]['children'] = $mon;
		}
		$this->success('日期信息', $year);
	}
	



}
